package com.ctgu.elasticsearch.utils;

import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.github.pagehelper.PageInfo;
import lombok.extern.log4j.Log4j2;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Log4j2
public class Tools {
    public static <T> ApiResult pageHelperResult(List<T> list, PageInfo<T> pageInfo, String TAG) {
        if (list.isEmpty()) {
            log.debug("{} : 获取列表为空 = {}", TAG, Collections.emptyList());
            return ApiResult.success("获取列表为空", Collections.emptyList());
        }
        PageData.PageDataBuilder<T> builder = PageData.builder();
        log.debug("{} : 获取列表成功 = {}", TAG, list);
        return ApiResult.success("获取列表成功", builder
                .totalNum(pageInfo.getTotal())
                .totalPage(pageInfo.getPages())
                .data(list)
                .build());
    }

    /**
     * @ Author: Alex
     * @ Description: ES 分页工具
     */
    public static <T> PageData<T> buildPageData(SearchResponse<T> response, int pageSize) {
        List<T> list = response.hits().hits().stream()
                .map(Hit::source)
                .collect(Collectors.toList());
        long totalHits = response.hits().total() != null ? response.hits().total().value() : 0;
        int totalPages = (int) ((totalHits + pageSize - 1) / pageSize);
        log.debug("获取列表成功 : {}", list);
        return PageData.<T>builder()
                .totalNum(totalHits)
                .totalPage(totalPages)
                .data(list)
                .build();
    }

    /**
     * @ Author: Alex
     * @ Description: 获取图片MD5
     */
    public static String getMd5(String url) {
        if (url.contains("aliyuncs.com")) {
            int lastSlash = url.lastIndexOf('/');
            int lastDot = url.lastIndexOf('.');
            if (lastSlash != -1 && lastDot != -1 && lastDot > lastSlash) {
                return url.substring(lastSlash + 1, lastDot);
            }
        } else if (url.contains("/image/")) {
            int startIndex = url.lastIndexOf("/image/") + "/image/".length();
            int endIndex = url.indexOf("?", startIndex);
            if (endIndex == -1) {
                endIndex = url.length();
            }
            return url.substring(startIndex, endIndex);
        }
        return null;
    }
}